package com.cinema.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jdt.internal.compiler.batch.Main;

import com.cinema.Bean.Admin;
import com.cinema.Bean.Hall;
import com.cinema.Bean.Movie;
import com.cinema.Bean.MovieSession;
import com.cinema.Bean.Seats;
import com.cinema.Bean.Ticket;
import com.cinema.Bean.User;
import com.cinema.dao.IHallDao;
import com.cinema.dao.IMovieDao;
import com.cinema.dao.IMovieSessionDao;
import com.cinema.dao.ISeatsDao;
import com.cinema.dao.ITicketDao;
import com.cinema.dao.IUserDao;
import com.cinema.dao.imp.HallDaoMysql;
import com.cinema.dao.imp.MovieDaoMysql;
import com.cinema.dao.imp.MovieSessionDaoMysql;
import com.cinema.dao.imp.SeatsDaoMysql;
import com.cinema.dao.imp.TicketDaoMysql;
import com.cinema.dao.imp.UserDaoMysql;

public class SeatsServlet extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
	ISeatsDao iSeatsDao = new SeatsDaoMysql();
	IMovieSessionDao iMovieSessionDao = new MovieSessionDaoMysql();
	ITicketDao ticketDao = new TicketDaoMysql();
	IMovieDao iMovieDao = new MovieDaoMysql();
    IUserDao userDao=new UserDaoMysql();
    IHallDao iHallDao = new HallDaoMysql();
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		String sessionId = req.getParameter("sessionId");// 场次
		MovieSession session = iMovieSessionDao.SelectById(sessionId);// 该场次
		List<Map<String, Object>> movieMessage = iSeatsDao.selectByWhere("sessionId='"+sessionId+"'");
		
		if ("initSeats".equals(method)) {
			// 初始化场厅位置
			// select se.* from seats se,session s where se.hallId=s.hallId and s.sessionId='S001';--查出当前场次 厅的所有位置
			// select t.seatCol,t.seatRow from session s,ticket t where t.sessionId='S001';--查出当前场次 厅已被购买的位置
			if (sessionId != null && sessionId != "") {
				List<Seats> seats = iSeatsDao.selectByHall(session.getHallId());// 该场厅所有位置
				List<Ticket> usedSeats = ticketDao.selectByWhere(sessionId);// 已购买位置
				
				req.setAttribute("sessionId",sessionId);// 场次
				req.setAttribute("movieMessage", movieMessage);//电影信息
				// 1.查询 电影票信息表 中是否该场次的座位哪些已被选
				req.setAttribute("seatsList", seats);//该场厅所有位置
				req.setAttribute("usedSeatsList", usedSeats);//该场厅已购买位置
	
			}
			// 将信息传到选座界面
			RequestDispatcher rd = req.getRequestDispatcher("/view/seats.jsp");
			rd.forward(req, resp);

		}else if("buyTicket".equals(method)){
			String[] split = req.getParameter("seatRow").split(",");
			String[] split2 = req.getParameter("seatCol").split(",");
			
			boolean flag = false;
		
				//全部购票成功，开始计算账户余额
				double totalPrice = Double.parseDouble(req.getParameter("totalPrice"));
				//执行修改操作呗
				User user=(User) req.getSession().getAttribute("loginUser");
				double balance = 0;
				if(null!=user){
					 balance = user.getBalance();
					if(balance<totalPrice){
						return;
					}
				}else{
					//未登录
					return;
				}
			List<Integer> buyedIds=new ArrayList<Integer>();//购买票的集合信息
			for(int i=0;i<split.length;i++){
				for(int j=0;j<split2.length;j++){
					int seatRow = Integer.parseInt(split[i]);
					int seatCol = Integer.parseInt(split2[j]);
					if(seatRow!=0&&seatCol!=0&&i==j){
						String userId = req.getParameter("userId");
						String hallId=session.getHallId();
						String movieId=session.getMovieId();
						Ticket u=new Ticket(userId, sessionId, seatRow, seatCol, hallId, movieId);
						int insert = 0;//抛异常怎么办
						try {
							insert = ticketDao.insert(u);
							buyedIds.add(insert);
							flag=true;
						} catch (Exception e) {
							e.printStackTrace();
							flag=false;
						}
						if(insert<1){
							flag=false;
						}
					}
				}
			}
			
			if(flag){
				//执行跟新
				user.setBalance(balance-totalPrice);
				int update = userDao.update(user);
				if(update>0){
					req.getSession().getAttribute("loginUser");
				}
			}
			resp.sendRedirect("/amberTimeCinema/seatsServlet?method=initSeats&sessionId="+sessionId);
		}else if("add".equals(method)) {
			String seatId = req.getParameter("seatId");
			String hallId = req.getParameter("hallId");
			String seatRow = req.getParameter("seatRow");
			String seatCount = req.getParameter("seatCount");
			
			Seats s = new Seats();
			s.setSeatId(seatId);
			s.setHallId(hallId);
			s.setSeatRow(Integer.parseInt(seatRow));
			s.setSeatCount(Integer.parseInt(seatCount));

			int insert = iSeatsDao.insert(s);

			if (insert == 1) {
				
				req.getSession().removeAttribute("seatslist");
			}
			resp.sendRedirect("Seats/index.jsp");
		}else if("delete".equals(method)) {
			String seatId = req.getParameter("seatId");
			if (seatId != null && seatId != "") {
				
				Seats s = new Seats();
				s.setSeatId(seatId);

				int delete = iSeatsDao.delete(s);

				if (delete == 1) {
					resp.getWriter().print("success"); 
					req.getSession().removeAttribute("seatslist");
				}else{
					
					resp.getWriter().print("error");
				}
			}
		}else if("getSeats".equals(method)){
			String seatId = req.getParameter("seatId");
			
			if(seatId!=null && seatId!=""){
				Seats seats = iSeatsDao.SelectById(seatId);
				req.setAttribute("seats", seats);
				
				// 所有场厅
				List<Hall> HallList=iHallDao.selectAll();
				req.setAttribute("HallList", HallList);
				
			}
			req.getRequestDispatcher("/Seats/edit.jsp").forward(req, resp);
		}else if("update".equals(method)){
			String seatId = req.getParameter("seatId");
			String hallId = req.getParameter("hallId");
			Integer seatRow = Integer.parseInt(req.getParameter("seatRow"));
			Integer seatCount = Integer.parseInt(req.getParameter("seatCount"));
			
			Seats s=new Seats(seatId, hallId, seatRow,seatCount);
			int update = iSeatsDao.update(s);
			if(update==1){
				req.getSession().removeAttribute("seatslist");
			}
			resp.sendRedirect("Seats/index.jsp");
		} else if ("select".equals(method)) {
			req.getSession().removeAttribute("seatslist");
			String keyword = req.getParameter("keyword");

			List<Seats> seats = iSeatsDao.Select(keyword);
			req.getSession().setAttribute("seatslist", seats);
		
		}else if("initTicketData".equals(method)){//初始化影票数据
			User user=(User) req.getSession().getAttribute("loginUser");
			String userId=user.getUserId();
			if (sessionId != null && sessionId != ""&&userId != null && userId != "") {
				List<Ticket> buyedTickets = ticketDao.selectBuyedTickets(sessionId, userId);
				req.setAttribute("buyedTickets",buyedTickets);// 场次
				req.setAttribute("movieMessage", movieMessage);
			}
			req.getRequestDispatcher("/view/ticket.jsp").forward(req, resp);
		}
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(req,resp);
		
	}

	public static void main(String[] args) {
		List<Ticket> seat = new ArrayList<Ticket>();
		Ticket ticket = new Ticket();
		ticket.setSeatRow(1);
		ticket.setSeatCol(1);
		seat.add(ticket);
		// 处理位置
		int[][] data = new int[3][3];
		
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[i].length; j++) {
				System.out.print(data[i][j] + "\t");
			}
			System.out.println();
		}
		
		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[i].length; j++) {
				for (int k = 0; k < seat.size(); k++) {
					if (i == seat.get(k).getSeatRow() - 1 && j == seat.get(k).getSeatCol() - 1) {
						data[i][j] = 1;
						break;
					}
				}
			}
		}

		for (int i = 0; i < data.length; i++) {
			for (int j = 0; j < data[i].length; j++) {
				System.out.print(data[i][j] + "\t");
			}
			System.out.println();
		}
	}
}
